<?php
/*
Plugin Name: joomlauth Plugin for Wordpress
Plugin URI:  http://hery.blaogy.org/2008/02/22/joomla-user-auth-for-wordpress-mu/
Description: Share users with joomla database
Version: 1.1.0
Author: Heriniaina Eugene
Author URI: http://hery.serasera.org


NB: This version now works for Joomla 1.0.x and 1.5.x
This version only works for  wp > 2.5
Check for joomlauth.php version < 1 for wp < 2.5

Todo: shared session
*/

// *** Begin Admin Config Functions *** //

$joomlauthVersion = "1.1.0";

load_plugin_textdomain('joomlauth','wp-content/mu-plugins/joomlauth/');

if (get_site_option("joomlauthActive")) {

	add_action('login_head', 'joomlauth_login_head');
	add_action('signup_header', 'joomlauth_signup_header');
	add_filter('show_password_fields', 'joomlauth_signup_getFalse');

}

function joomlauth_signup_() {
	return false;
}	

function joomlauth_login_head()
{
	global $errors;
	$wp_error = $errors;

	// If cookies are disabled we can't log in even with a valid user+pass
	if ( isset($_POST['testcookie']) && empty($_COOKIE[TEST_COOKIE]) )
	$wp_error->add('test_cookie', __("<strong>ERROR</strong>: Cookies are blocked or not supported by your browser. You must <a href='http://www.google.com/cookies.html'>enable cookies</a> to use WordPress.", 'joomlauth'));

	// Some parts of this script use the main login form to display a message
	//the first message is removed bcs already sent by wp
	//if		( isset($_GET['loggedout']) && TRUE == $_GET['loggedout'] )			$wp_error->add('loggedout', __('You are now logged out.', 'joomlauth'), 'message');
	elseif	( isset($_GET['registration']) && 'disabled' == $_GET['registration'] )	$wp_error->add('registerdiabled', __('User registration is currently not allowed.', 'joomlauth'));
	elseif	( isset($_GET['checkemail']) && 'confirm' == $_GET['checkemail'] )	$wp_error->add('confirm', __('Check your e-mail for the confirmation link.', 'joomlauth'), 'message');
	elseif	( isset($_GET['checkemail']) && 'newpass' == $_GET['checkemail'] )	$wp_error->add('newpass', __('Check your e-mail for your new password.', 'joomlauth'), 'message');
	elseif	( isset($_GET['checkemail']) && 'registered' == $_GET['checkemail'] )	$wp_error->add('registered', __('Registration complete. Please check your e-mail.', 'joomlauth'), 'message');
	


	if ( $wp_error->get_error_code() ) {
		$errors = array();
		
		foreach ( $wp_error->get_error_codes() as $code ) {
			$severity = $wp_error->get_error_data($code);
			foreach ( $wp_error->get_error_messages($code) as $error ) {
				$errors[] = $error;
			}
		}
		if ( !empty($errors) )
		{
			$login_error = join('<br />', $errors);
		}
	}
	
	
	if($_GET['loggedout'] == "true" && $redirect = get_site_option("joomlauthLogoutURL")) {
			echo "
				<script language=\"javascript\"
				type=\"text/javascript\">
				<!--
				window.location.replace(
				\"$redirect\");
				-->
				</script>
			";
			exit;
	}	
	
	//I've tested, there is no risk of looping
	if (get_site_option("joomlauthLoginURL") && ereg('wp-admin', get_site_option("joomlauthLoginURL")) === false && ereg('wp-login', get_site_option("joomlauthLoginURL")) === false)
	{
	echo "
		<script language=\"javascript\"
		type=\"text/javascript\">
		<!--
		window.location.replace(
		\"". get_site_option("joomlauthLoginURL")  . "?login_error=". $login_error."\");
		-->
		</script>
	";
		exit;
	}
	
}




function joomlauth_signup_header() {
	if($redirect = get_site_option("joomlauthSignupURL")) {
		echo "
			<script language=\"javascript\" type=\"text/javascript\">
			<!--
			window.location.replace(
			\"$redirect\");
			-->
			</script>";
		exit;
	}

}

add_action('admin_menu', 'joomlauth_addmenu');
function joomlauth_addmenu() {
	$objCurrUser = wp_get_current_user();
	$objUser = wp_cache_get($objCurrUser->id, 'users');
	if (function_exists('add_options_page') && is_site_admin($objUser->user_login)) {
		add_options_page('Authentication Options', 'Joomla Auth Options', 9, basename(__FILE__), 'joomlauthOptionsPanel');
	}
}
require_once( ABSPATH . WPINC . '/registration.php');

function joomlauth_Auth($username, $password) {
	global $wpdb;

	$joomlauthDbHost 		= get_site_option("joomlauthDbHost");
	$joomlauthDbUser 		= get_site_option("joomlauthDbUser");
	$joomlauthDbName		= get_site_option("joomlauthDbName");
	$joomlauthDbPass		= get_site_option("joomlauthDbPass");
	$joomlauthDbPrefix		= get_site_option("joomlauthDbPrefix");
	
	

	$link = mysql_connect($joomlauthDbHost, $joomlauthDbUser, $joomlauthDbPass, true) or die('Not connected : ' . mysql_error());

	// make foo the current db
	$mydb = mysql_select_db($joomlauthDbName, $link) or die ('Can\'t use $joomlauthDbName : ' . mysql_error());
	
	//get by username
	$sql = "SELECT name, username, password, email FROM " . $joomlauthDbPrefix . "users WHERE LOWER(username)='" . mysql_real_escape_string(strtolower($username)) . "' LIMIT 1";
	
	if($result = mysql_query($sql)) { 
		while ($row = mysql_fetch_array($result)) {
			//var_dump($row);
			//get joomla password to verify if it is joomla 1.5.x or 1.0.x
			$_salt = "";
			$_parts = "";

			$_parts	= (strlen($row["password"]) > 32) ? explode( ':', $row["password"] ) : array();
			$_salt = $_parts[1];
			$_crypt		=	md5( $password . $_salt );
			//var_dump($password);
			$_hashedPwd	=	$_crypt. ($_salt ? ':' . $_salt : '');
			//var_dump($_hashedPwd);
			if($_hashedPwd == $row["password"]) {

				return $row;
			} else {
				Return false;
			}
			
		}
	} else {
		Return false;
	}


}
function joomlauthOptionsPanel() {
	global $joomlauthVersion;
	//var_dump($_POST);
	if($_POST['joomlauthOptionsSave']) {
		update_site_option('joomlauthSignupURL', $_POST['joomlauthSignupURL']);
		update_site_option('joomlauthLogoutURL', $_POST['joomlauthLogoutURL']);
		update_site_option('joomlauthDbHost', $_POST['joomlauthDbHost']);
		update_site_option('joomlauthDbUser', $_POST['joomlauthDbUser']);
		update_site_option('joomlauthDbName', $_POST['joomlauthDbName']);
		update_site_option('joomlauthDbPass', $_POST['joomlauthDbPass']);
		update_site_option('joomlauthDbPrefix', $_POST['joomlauthDbPrefix']);
		update_site_option('joomlauthActive', $_POST['joomlauthActive']);
		update_site_option('joomlauthGetBlog', $_POST['joomlauthGetBlog']);
		update_site_option('joomlauthLoginURL', $_POST['joomlauthLoginURL']);
	
		echo "<div class='updated'><p>" . __("Saved Options!", 'joomlauth') . "</p></div>";
	}
	
	$joomlauthSignupURL 	= get_site_option("joomlauthSignupURL");
	$joomlauthLogoutURL 	= get_site_option("joomlauthLogoutURL");
	$joomlauthDbHost 		= get_site_option("joomlauthDbHost");
	$joomlauthDbUser 		= get_site_option("joomlauthDbUser");
	$joomlauthDbName		= get_site_option("joomlauthDbName");
	$joomlauthDbPass		= get_site_option("joomlauthDbPass");
	$joomlauthDbPrefix		= get_site_option("joomlauthDbPrefix");
	$joomlauthActive		= get_site_option("joomlauthActive");
	$joomlauthGetBlog		= get_site_option("joomlauthGetBlog");
	$joomlauthLoginURL		= get_site_option("joomlauthLoginURL", get_option('siteurl') . "/wp-admin");

	if($joomlauthActive == '1') {
		$tChecked = "checked";
	}
	else {
		$fChecked = "checked";
	}

	if($joomlauthGetBlog == '1') {
		$joomlauthGetBlog1 = "checked";
	} else {
		$joomlauthGetBlog0 = "checked";
	}
	
	?>
	<div class="wrap">
	<h2>joomlauth Authentication Options</h2>
		<small>Version: <?php echo $joomlauthVersion?> : <a href="http://hery.blaogy.org/2008/02/22/joomla-user-auth-for-wordpress-mu/"><?php _e('Click here for update' , 'joomlauth')?></a></small>
	<form method="post" id="joomlauth_options">

	<p class="submit"><input type="submit" value="Save" name="joomlauthOptionsSave"/></p>

		<fieldset class="options">
		<legend><?php _e('Authentication options', 'joomlauth')?></legend>
	
		<table class="optiontable">
			<tbody>
				<tr valign="top">
					<th scope="row"><?php _e('Database host:', 'joomlauth')?></th>
					<td>
					<input type='text' name='joomlauthDbHost' value='<?php echo $joomlauthDbHost ?>' style='width: 300px;' /><br />
					<em><?php _e('This is usually localhost.', 'joomlauth')?></em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Database username:', 'joomlauth')?></th>
					<td>
					<input type='text' name='joomlauthDbUser' value='<?php echo $joomlauthDbUser?>' style='width: 300px;' /><br />
					<em><?php _e('Username to access the database.', 'joomlauth')?></em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Database password:', 'joomlauth')?></th>
					<td>
					<input type='password' name='joomlauthDbPass' value='<?php echo $joomlauthDbPass?>' style='width: 300px;' /><br />
					<em><?php _e('Your database password.', 'joomlauth')?></em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Database name:', 'joomlauth')?></th>
					<td>
					<input type='text' name='joomlauthDbName' value='<?php echo $joomlauthDbName?>' style='width: 300px;' /><br />
					<em><?php _e('Name of the database where users are stored.', 'joomlauth')?></em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Database table prefix:', 'joomlauth')?></th>
					<td>
					<input type='text' name='joomlauthDbPrefix' value='<?php echo $joomlauthDbPrefix?>' style='width: 300px;' /><br />
					<em><?php _e('Prefix of joomla tables example jos_ .', 'joomlauth')?></em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Sign-up URL:', 'joomlauth')?></th>
					<td>
					<input type='text' name='joomlauthSignupURL' value='<?php echo $joomlauthSignupURL?>' style='width: 300px;' /><br />
					<em><?php _e('Where people go to register to your blog', 'joomlauth')?> </em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Login form URL:', 'joomlauth')?></th>
					<td>
					<input type='text' name='joomlauthLoginURL' value='<?php echo $joomlauthLoginURL?>' style='width: 300px;' /><br />
					<em><?php _e('Where users is the Login Form', 'joomlauth')?></em>
					</td>
				</tr>				
				<tr valign="top">
					<th scope="row"><?php _e('Logout URL:', 'joomlauth')?></th>
					<td>
					<input type='text' name='joomlauthLogoutURL' value='<?php echo $joomlauthLogoutURL?>' style='width: 300px;' /><br />
					<em><?php _e('Where users are redirected when logged out', 'joomlauth')?></em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Should user get a blog?', 'joomlauth')?></th>
					<td>
						<input type='radio' name='joomlauthGetBlog' value='1' <?php echo $joomlauthGetBlog1 ?> /> <?php _e('Yes', 'joomlauth')?> <br />
						<input type='radio' name='joomlauthGetBlog' value='0' <?php echo $joomlauthGetBlog0 ?>/> <?php _e('No account only', 'joomlauth')?>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><?php _e('Enable joomlauth plugin?', 'joomlauth')?></th>
					<td>
						<input type='radio' name='joomlauthActive' value='1' <?php echo $tChecked ?>/> <?php _e('Yes', 'joomlauth')?> <br />
						<input type='radio' name='joomlauthActive' value='0' <?php echo $fChecked ?>/> <?php _e('No', 'joomlauth')?> 
					</td>
				</tr>
			</tbody>
		</table>
		</fieldset>
 		<p class="submit"><input type="submit" name="joomlauthOptionsSave" value="<?php _e('Save', 'joomlauth')?>" /></p>
	</form>
	</div>
	<?php
}
// *** End Admin Config Functions *** //


// *** Begin User Auth Functions *** //

// This will disabled the change password dialogs.



if (get_site_option("joomlauthActive")) {

function wp_authenticate($username, $password) {
	global $wpdb, $error, $current_site, $current_user, $base;
	
	//Make sure we always use lowercase usernames.
	$username = strtolower($username);
	
	$joomlauthActive 		= get_site_option("joomlauthActive");
	$joomlauthSignupURL 	= get_site_option("joomlauthSignupURL");
	$joomlauthLogoutURL 	= get_site_option("joomlauthLogoutURL");
	$joomlauthDbHost 		= get_site_option("joomlauthDbHost");
	$joomlauthDbUser 		= get_site_option("joomlauthDbUser");
	$joomlauthDbName		= get_site_option("joomlauthDbName");
	$joomlauthDbPass		= get_site_option("joomlauthDbPass");
	$joomlauthDbPrefix		= get_site_option("joomlauthDbPrefix");
	$joomlauthGetBlog		= get_site_option("joomlauthGetBlog");
	
	if(!$username) {
		$error = __('<strong>Error</strong>: The username field is empty.', 'joomlauth');
		return new WP_Error('wrong_password', $error);
	}
	
	if(!$password) {
		$error = __('<strong>Error</strong>: The password field is empty.', 'joomlauth');
		return new WP_Error('wrong_password', $error);
	}
	$login = get_userdatabylogin($username);
	//Bassically if we are already logged in and we try to relogin.
	if ($current_user->data->user_login == $username) {
		return new WP_User($login->ID);
	}



	//everything is ok
	//var_dump($login);
	//var_dump(md5($password));
	if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
		return new WP_User($login->ID);
	}
	//only username is ok => check from external and update the password
	if($login->user_login == $username) {
		if($juser = joomlauth_Auth($username, $password)) {
			if(strtolower($juser['username']) == $username) { //just doublechecking
				$query = "UPDATE $wpdb->users SET user_pass='" . md5($password) . "' WHERE ID = '$login->ID'";
				$query = apply_filters('update_user_query', $query);
				$wpdb->query( $query );
				return new WP_User($login->ID);
			} else {
				$error = __('<strong>Error</strong>: Wrong password.', 'joomlauth');
				return new WP_Error('wrong_password', $error);
			}
		}
	} else {
		// a complete new user from the external database
	
		if($juser = joomlauth_Auth($username, $password)) {	
			// call the registration function to create a wordpress user account for this
			// successfully authenticated user
			require_once( ABSPATH . WPINC . '/registration.php');
				
			if ( !username_exists( $username ) ) { //no need of this???
				//Create the user

				define( "WP_INSTALLING", true );
				$user_id = wpmu_create_user( $username, $password, $juser[email] );
				
				if (!$user_id) {
					$error = __('<strong>Error</strong>: Account Creation Failed.', 'joomlauth');
					return new WP_Error('wrong_password', $error);
				}
				
				//Update their first and last name from ldap

				update_usermeta( $user_id, 'last_name', ($juser[name] ? $juser[name] : $username ));
					
				//This is for plugin events
				do_action( 'wpmu_new_user', $user_id );
				do_action('wpmu_activate_user', $user_id, $password);
					
				$domain = strtolower( wp_specialchars( $username ) );
				if( constant( "VHOST" ) == 'yes' ) {
					$newdomain = $domain . "." . $current_site->domain;
					$path = $base;
				} else {
					$newdomain = $current_site->domain;
					$path = $base . $domain . '/';
				}
					

				if (get_site_option("joomlauthGetBlog")) {
					//create blog
					
					/*
					Thanks to atmaniak 
					- joomla accepts username with space so needs sanitize_username
					*/
					
					$meta = apply_filters('signup_create_blog_meta', array ( 'public' => 1));
					$blog_id = wpmu_create_blog($newdomain, $path, sanitize_username($username) , $user_id, $meta); 
					do_action('wpmu_activate_blog', $blog_id, $user_id, $password, sanitize_username($username), $meta); 
				}

				//Must recreated the login object for our shiny NEW users.
				$login = get_userdatabylogin($username);
				
				//Setup redirection to users home directory.
				if (!strpos($_REQUEST['redirect_to'], $username)) {
					$_REQUEST['redirect_to'] = $username . "/" . $_REQUEST['redirect_to'];
				}
				return new WP_User($login->ID);
			} elseif ( !username_exists( $username ) && !$seraseraCreateAcct ) {
				$error = __('<strong>Error</strong>: Local account does not exist.', 'joomlauth');
				return new WP_Error('wrong_password', $error);
			}

		} else {
			$error = __('<strong>Error</strong>: Wrong login and password.', 'joomlauth');
			return new WP_Error('wrong_password', $error);
		}
		
				
		//At this point we must have a login object!
		//I dont see how we couldn't but just in case.
		if (!$login) {
			$error = sprintf(__('<strong>Error</strong>: Unknown Near %s in %s' , 'joomlauth') , __LINE__ , __FILE__ );
			return new WP_Error('wrong_password', $error);
		}
		
		//Added to atempt to recreate login correctly
		//I think this is for account suspentions
		$primary_blog = get_usermeta( $login->ID, "primary_blog" );
		if( $primary_blog ) {
			$details = get_blog_details( $primary_blog );
			if( is_object( $details ) ) {
				if( $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) {
					$error = __('<strong>Error</strong>: Blog suspended.', 'joomlauth');
					return new WP_Error('wrong_password', $error);
				}
			}
		}
				


		return new WP_Error('wrong_password', $error);
	} // End if ()


		if (!$login) {
			if( is_site_admin( $username ) ) {
				//If Site Admin
				//FYI This does exactly the same thing as $login = get_userdatabylogin( $username );
				//which has already been done above?!?
				unset( $login );
				$userdetails = get_userdatabylogin( $username );
				$login->user_login = $username;
				$login->user_pass = $userdetails->user_pass;
			} else {
				//If Domain Admin
				$admins = get_admin_users_for_domain();
				reset( $admins );
				while( list( $key, $val ) = each( $admins ) ) 
				{ 
					if( $val[ 'user_login' ] == $username ) {
						unset( $login );
						$login->user_login = $username;
						$login->user_pass  = $val[ 'user_pass' ];
					}
				}
			}
		}
		
		if (!$login) {
			//If we didnt find a user originally and we didnt get one from the above code...
			$error = __('<strong>Error</strong>: Wrong username.', 'joomlauth');
			return new WP_Error('wrong_password', $error);
		} else {
			//Setup some kind of default blog for the user...
			$primary_blog = get_usermeta( $login->ID, "primary_blog" );
			if( $primary_blog ) {
				$details = get_blog_details( $primary_blog );
				if( is_object( $details ) ) {
					if( $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) {
						$error = __('<strong>Error</strong>: Blog suspended.', 'joomlauth');
						return new WP_Error('wrong_password', $error);
					}
				}
			}
			
			//Setup redirection to users home directory.
			if (!strpos($_REQUEST['redirect_to'], $username)) {
				$_REQUEST['redirect_to'] = $username . "/" . $_REQUEST['redirect_to'];
			}
			
			// If the password is already_md5, it has been double hashed.
			// Otherwise, it is plain text.
			if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
				return new WP_User($login->ID);
			} else {
				$error = __('<strong>Error</strong>: Incorrect password.', 'joomlauth');
				$pwd = '';
				return new WP_Error('wrong_password', $error);
			}
		}
	}
}
?>
